using MediatR;
using RBAC_Class.Domain;
using RBAC_Class.ErrorCode;
using RBAC_Class.Infrastructrue.Interfaces;
using RBAC_Class.Write.API.Application.Command.Users;
using System;
using NLog;

namespace RBAC_Class.Write.API.Application.CommandHandler.Users
{
    public class AddUserCommandHandler : IRequestHandler<AddUserCommand, APIResult<int>>
    {
        private readonly IBaseRepository<User> userRep;
        private readonly IBaseRepository<UserRole> userRoleRep;
        private readonly ILogger<AddUserCommandHandler> logger;

        public AddUserCommandHandler(IBaseRepository<User> userRep, IBaseRepository<UserRole> userRoleRep, ILogger<AddUserCommandHandler> logger)
        {
            this.userRep = userRep;
            this.userRoleRep = userRoleRep;
            this.logger = logger;
        }

        public Task<APIResult<int>> Handle(AddUserCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var user = new User
                {
                    UserName = request.UserName,
                    Password = request.Password, // 建议加密
                    Status = 1,
                    CreateTime = DateTime.Now,
                    IsDelete = false
                };
                userRep.Add(user);

                foreach (var roleId in request.RoleIDs)
                {
                    var userRole = new UserRole
                    {
                        UserID = user.UserID,
                        RoleID = roleId,
                        CreateTime = DateTime.Now,
                        IsDelete = false
                    };
                    userRoleRep.Add(userRole);
                }

                return Task.FromResult(new APIResult<int>
                {
                    Code = ResultCode.Success,
                    Message = "添加成功",
                    Data = user.UserID
                });
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "添加用户失败 - 用户名: {UserName}, 角色IDs: {RoleIDs}", 
                    request.UserName, string.Join(",", request.RoleIDs));
                throw;
            }
        }
    }
} 